package njust.edu.controller;

import njust.edu.entity.Dish;
import njust.edu.entity.User;
import njust.edu.service.DishService;
import njust.edu.service.impl.DishServiceImpl;
import njust.edu.web.Cart;
import njust.edu.web.CartItem;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

@WebServlet(name = "CartController", value = "/CartController")
public class CartController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    //设置桌号
    public void tableNumChange(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String tableNum = request.getParameter("tableNum");
        HttpSession session = request.getSession();
        session.setAttribute("tableNum", tableNum);
    }

    //购物车界面
    public void toCartUI(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        request.setAttribute("user",user);
        Cart cart = (Cart) session.getAttribute("cart");
        request.setAttribute("cart",cart);
        request.getRequestDispatcher("WEB-INF/jsp/cart/cart.jsp").forward(request, response);
    }

    //清空购物车
    public void cancel(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        ServletContext servletContext = request.getSession().getServletContext();
        Cart cartStock = (Cart) servletContext.getAttribute("cartStock");
        if(cart != null && cartStock!=null){
            for(CartItem c:cart.getItems()){
                Integer old = c.getQuantity();
                cartStock.updateItemQuantity(c.getDish().getId(), old-c.getQuantity());
            }
        }
        cart.clear();
        response.sendRedirect("BookController?method=toIndexUI");
    }

    class ChangeResult {
        int num;
        int totalNumber;
        float totalMoney;
    }

    //份数减一
    public void cartItemDelete(HttpServletRequest request,
                               HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
//        ServletContext servletContext = request.getSession()
//                .getServletContext();
//        Cart cartStock = (Cart) servletContext.getAttribute("cartStock");
        String id = request.getParameter("id");
        Integer quantity = cart.getItemNum(id);
        cart.removeItem(id);
//        Integer ApplocationQuantity = cartStock.getItemNum(id);
//        cartStock.updateItemQuantity(id, ApplocationQuantity - quantity);
        response.sendRedirect("CartController?method=toCartUI");
    }

    //份数加一
    public void cartItemAdd(HttpServletRequest request,
                               HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
//        ServletContext servletContext = request.getSession()
//                .getServletContext();
//        Cart cartStock = (Cart) servletContext.getAttribute("cartStock");
        String id = request.getParameter("id");
        Integer quantity = cart.getItemNum(id);
        cart.addOne(id);
//        Integer ApplocationQuantity = cartStock.getItemNum(id);
//        cartStock.updateItemQuantity(id, ApplocationQuantity - quantity);
        response.sendRedirect("CartController?method=toCartUI");
    }

    DishService dishService = new DishServiceImpl();

    //添加到购物车
    public void addToCart(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        ServletContext servletContext = request.getSession().getServletContext();
        HttpSession session = request.getSession();
        String idStr = request.getParameter("id");
        String id = idStr;
        Cart cart = (Cart) session.getAttribute("cart");
//         Cart cartStock = (Cart) servletContext.getAttribute("cartStock");

        if (cart == null) {
            cart = new Cart();
            session.setAttribute("cart", cart);
        }
//        String result = "false";
        PrintWriter out = response.getWriter();
        try {
            Dish dish = dishService.getDishById(id);
            // 获取未付款正在购物车中的数目
//             Integer stockNum = cartStock.getItemNum(id);
            cart.addDish(dish);
//            System.out.println(dish.getId());
//            if (dishService.checkStock(id, stockNum)) {
//                result = "true";
//                cartStock.addDish(dish);
//                cart.addDish(dish);
//            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
//        if (result.equals("true")) {
//            result = cart.getTotalNumber() + "";
//        }
        //out.write(result);
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String methodName = request.getParameter("method");
        try {
            Method method = getClass().getDeclaredMethod(methodName,
                    HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}
